<?php
/**
 *
 * @notes:
 * @author:     Jokenzhang
 * @time:       2020/12/23  10:31
 * @version:    V20201223.1.1
 *
 */

namespace Modules\Article\Service;


class TemplateService
{
    /**
     * @Notes:  获取所有的模板
     * @Interface:          all
     * @return:             array
     * @author:             Jokenzhang
     * @Time:               2020/12/23  10:56
     */
    public function all()
    {
        $dirs = glob(public_path('templates/*'));
        $configs = [];
        foreach ($dirs as $dir) {
            if ($config = $this->parseConfig($dir)) {
                $configs[] = $config;
            }
        }
        return $configs;
    }

    /**
     * @Notes:  将配置文件转换成可用的数组格式
     * @Interface:          parseConfig
     * @param $dir
     * @return:             array|mixed
     * @author:             Jokenzhang
     * @Time:               2020/12/23  10:57
     */
    public function parseConfig($dir)
    {
        $file = $dir . '/package.json';
        if (is_file($file)) {
            $jsonContent = file_get_contents($file);
            $config = json_decode(trim($jsonContent));
            if (is_object($config)) {
                $config = (array)$config;
                $name = basename($dir);
                $config['preview'] = url('templates/' . $name . '/' . $config['preview']);
                $config['name'] = $name;
                return $config;
            }
        }
    }
}
